﻿define([
  'models/abmManagers/userManager',
  'models/abmManagers/companyManager',
  'models/abmManagers/rolManager',
  'models/abmManagers/groupManager',
  'text!templates/abmManagers/abmBaseTmp.html',
  'text!templates/abmManagers/abmFormTmp.html',
  'text!templates/abmManagers/user/super/userEdit.html',
  'text!templates/abmManagers/user/super/userEditCmpyItem.html',
], function (UserModel, CompanyModel, RolModel, GroupModel, BaseTmp,
                FormTmp, UniqTmp, cmpyItemTemplate) {
    var view = Backbone.View.extend({
        el: $("#main"),
        _uId: "",
        _userData: {},
        render: function () {
            $("#mainLoading").show();
            $("div[data-rel='abm-user']").remove();
            var _this = this;
            this._uId = $.uuid();

            var companies = new CompanyModel();
            var users = new UserModel();

            users.GetUser(this.options.userId, function (dataUser) {
                // almacenar user en variable ?? <<<<<<<<<<
                _this._userData = dataUser;
                companies.List(function (dataCompany) {
                    var baseTemplate = Handlebars.compile(BaseTmp);
                    var formTemplate = Handlebars.compile(FormTmp);
                    var uniqTemplate = Handlebars.compile(UniqTmp);

                    var dataBaseTemplate = {
                        id: _this._uId,
                        dataRel: "abm-user", // cuidado, ref en js
                        tmpClass: "user-edit", // cuidado, ref en css
                        title: translate("_editUser")
                    };
                    var dataUniqTemplate = {
                        user: dataUser,
                        company: dataCompany
                    };

                    var html = baseTemplate(dataBaseTemplate);
                    var html2 = formTemplate();
                    var html3 = uniqTemplate(dataUniqTemplate);
                    
                    _this.$el.append(html);
                    $("div[data-id='" + _this._uId + "']").find("div.abm-content").append(html2);
                    $("div[data-id='" + _this._uId + "']").find("div.form-content").append(html3);
                    // Fx p/cargar combos
                    //_this.initialValues(dataUser);
                    _this.initialValues();
                    
                    postRender(_this.$el.find("div[data-id='" + _this._uId + "']"));

                    _this.addHandlers();
                    $("#mainLoading").hide();
                });
            });
        },
        //initialValues: function (user) {
        initialValues: function (user) {
            var listCompanies = $("div[data-id='" + this._uId + "']").find("div.user-company-items");
            var groups = [], roles = [];
            for (var k = 0; k < listCompanies.length; k++) {
                var userCompanyId = $(listCompanies[k]).find("div.user-company-assigned").attr("data-value");
                var _itemGroupFromList = $(listCompanies[k]).find("div.user-group a");
                var _itemRolFromList = $(listCompanies[k]).find("div.user-rol a");
                //this.chargeRolNGroup(user, userCompanyId, _itemRolFromList, _itemGroupFromList);
                this.chargeRolNGroup(userCompanyId, _itemRolFromList, _itemGroupFromList);
            }
        },//_this._userData
        //chargeRolNGroup: function (user, userCompanyId, contextRol, contextGroup) {
        chargeRolNGroup: function (userCompanyId, contextRol, contextGroup) {
            var _this = this;
            // Carga de roles
            var rols = new RolModel().List(userCompanyId, $.proxy(function (dataRol) {
                if (dataRol.length > 0) { // si la company tiene roles
                    var _rolItem = this;
                    var rolList = [{ value: "", text: "" }];

                    for (var ii = 0; ii < dataRol.length; ii++) {
                        rolList[ii] = {
                            value: dataRol[ii].rolId,
                            text: dataRol[ii].name
                        }
                    }
                    _rolItem.editable({
                        pk: 1,
                        source: rolList,
                        success: function (response, newValue) {
                            $(this).attr("data-value", newValue);
                        }
                    });
                }
            }, contextRol));
            // Carga de grupos
            var groups = new GroupModel().List(userCompanyId, $.proxy(function (dataGroup) {
                if (dataGroup.length > 0) { // si la company tiene grupos
                    var _groupItem = this;
                    var assignedGroups = [""];
                    var groupsList = [{ value: "", text: "" }];
                    //for (var i = 0; i < user.userCompanies.length; i++) {
                    for (var i = 0; i < _this._userData.userCompanies.length; i++) {
                        //if (user.userCompanies[i].companyId == userCompanyId) {
                        if (_this._userData.userCompanies[i].companyId == userCompanyId) {
                            for (var jj = 0; jj < _this._userData.userCompanies[i].groups.length; jj++) {
                                assignedGroups[jj] = _this._userData.userCompanies[i].groups[jj].groupId;
                            //for (var jj = 0; jj < user.userCompanies[i].groups.length; jj++) {
                                //assignedGroups[jj] = user.userCompanies[i].groups[jj].groupId;
                            };
                            break;
                        }
                    }
                    for (var i = 0; i < dataGroup.length; i++) {
                        groupsList[i] = {
                            value: dataGroup[i].groupId,
                            text: dataGroup[i].name
                        }
                    };
                    _groupItem.editable({
                        pk: 1,
                        value: assignedGroups,
                        source: groupsList,
                        success: function (response, newValue) {
                            $(this).attr("data-value", newValue);
                        }
                    });
                }
            }, contextGroup));
        },
        save: function () {
            var _uId = this._uId;
            var _this = this;

            var _userForm = $("div[data-id='" + _uId + "']").find("form");
            if (!$(_userForm).validate().errorList.length > 0) {
                var listCompanies = $("div[data-id='" + _uId + "']").find("div.user-company-items");
                if (listCompanies.length > 0) {
                    _this._userData.name = $("div[data-id='" + _uId + "']").find("div.user-name input").val();
                    _this._userData.userLogin = $("div[data-id='" + _uId + "']").find("div.user-login input").val();
                    _this._userData.password = $("div[data-id='" + _uId + "']").find("div.user-password input").val();
                    _this._userData.email = $("div[data-id='" + _uId + "']").find("div.user-email input").val();
                    _this._userData.state = '0' != $("div[data-id='" + _uId + "']").find("div.user-state input").val();

                    var userCompanyId = "", _rolId = "", groupItem = "";//, userCompaniesData = [];

                    for (var j = 0; j < _this._userData.userCompanies.length; j++) {
                        for (var k = 0; k < listCompanies.length; k++) {
                            userCompanyId = $(listCompanies[k]).find("div.user-company-assigned").attr("data-value");
                            if (_this._userData.userCompanies[j].companyId == userCompanyId) {
                                // Asignacion de roles
                                _rolId = $(listCompanies[k]).find("div.user-rol a div").attr("data-value");
                                if (_rolId == undefined) {
                                    _rolId = $(listCompanies[k]).find("div.user-rol a").attr("data-value");
                                }
                                _this._userData.userCompanies[j].rolId = _rolId;
                                // Asignacion de grupos
                                _groupItem = $(listCompanies[k]).find("div.user-group a");
                                var assignedGroups = [];

                                var auxRowGroups = $(_groupItem).attr("data-value");
                                if (auxRowGroups != undefined) {
                                    var splitGroups = auxRowGroups.split(",");

                                    for (var h = 0; h < splitGroups.length; h++) {
                                        assignedGroups[h] = {
                                            groupId: splitGroups[h]
                                        };
                                    }
                                } else {
                                    var auxRowGroup = "";
                                    for (var h = 0; h < _groupItem.find("div").length; h++) {
                                        assignedGroups[h] = {
                                            groupId: $(_groupItem.find("div")[h]).attr("data-value")
                                        };
                                    }
                                }
                                _this._userData.userCompanies[j].groups = assignedGroups;
                            }
                        }
                    }
                    
                    new UserModel().Update(_this._userData, function () {
                        require(['controllers/abmManagers/userManager'], function (Controller) {
                            (new Controller()).show();
                        });
                    });
                } else
                    $.gritter.add({
                        title: translate("_wait"),
                        text: translate("_noCompanyAssigned"),
                        image: null,
                        time: '3000'
                    });
            }
        },
        changeState: function () {
            this.checked ? $(this).attr('value', 1) : $(this).attr('value', 0);
        },
        refreshListLabels: function () {
            $("div[data-id='" + this._uId + "']").find("div.cmpy-list").css({
                "display": ($("div[data-id='" + this._uId + "']").find("div.user-company-assigned").length == "0") ? "none" : "inline-block"
            });
        },
        addUserCompany: function () {
            var _this = this;
            var divToAddUser = $("div[data-id='" + _this._uId + "']").find("div.user-cmpy");
            
            var listCompanies = $("div[data-id='" + _this._uId + "']").find("div.user-company-assigned");
            // lee company seleccionada
            var selCmpyId = $("div[data-id='" + _this._uId + "']").find("div.add-company select").val();
            for( var i = 0 ; i < listCompanies.length ; i++){
                if ($(listCompanies[i]).attr("data-value") == selCmpyId) {
                    $.gritter.add({
                        title: translate("_wait"),
                        text: translate("_companyAlreadyAssigned"),
                        image: null,
                        time: '3000'
                    });
                    return;
                }
            }
            var cmpyMod = new CompanyModel(),
                rolMod = new RolModel(),
                groupMod = new GroupModel();
            var template = Handlebars.compile(cmpyItemTemplate);
            cmpyMod.GetCompany(selCmpyId, function (dataCompany) {
                rolMod.List(selCmpyId, function (dataRol) {
                    groupMod.List(selCmpyId, function (dataGroup) {
                        var data = {
                            groups: dataGroup,
                            rol: dataRol,
                            company: dataCompany
                        }
                        var html = template(data);
                        this.$(divToAddUser).append(html);
                        var newItem = $(divToAddUser).find("div.user-company-items").last();
                        if (dataRol.length > 0) { // si la company tiene roles
                            var _rolItem = $(newItem).find("div.user-rol a");
                            var rolList = [{ value: "", text: "" }];

                            for (var ii = 0; ii < dataRol.length; ii++) {
                                rolList[ii] = {
                                    value: dataRol[ii].rolId,
                                    text: dataRol[ii].name
                                }
                            }
                            _rolItem.editable({
                                pk: 1,
                                source: rolList,
                                success: function (response, newValue) {
                                    $(this).attr("data-value", newValue);
                                }
                            });
                        }

                        if (dataGroup.length > 0) { // si la company tiene grupos
                            var _groupItem = $(newItem).find("div.user-group a");
                            
                            var groupsList = [{ value: "", text: "" }];

                            for (var i = 0; i < dataGroup.length; i++) {
                                groupsList[i] = {
                                    value: dataGroup[i].groupId,
                                    text: dataGroup[i].name
                                }
                            };
                            _groupItem.editable({
                                pk: 1,
                                source: groupsList,
                                success: function (response, newValue) {
                                    $(this).attr("data-value", newValue);
                                }
                            });
                        }
                        $(newItem).find("a.btn-removeCompany").on("click", $.proxy(function () {
                            _this.removeUserCompany(event);
                            return false;
                        }, _this));
                    });
                });
            });
        },
        removeUserCompany: function (e) {
            var _toRemove = $(e.currentTarget).parent("div").parent("div");
            var _this = this;

            require(['controllers/common/showModal'], function (Controller) {
                (new Controller()).show(
                    {
                        title: translate("_deleteUserCompany"),
                        text: translate("_sure_delete_user_company"),
                        buttons: [
                            { "title": translate("yes"), "css": "primary", "code": "yes" },
                            { "title": translate("no"), "code": "no" }
                        ],
                        callback: function (code) {
                            if (code == "yes") {
                                $("#mainLoading").show();
                                _toRemove.prev("hr").remove();
                                _toRemove.remove();
                                _this.refreshListLabels();
                                $("#mainLoading").hide();
                            }
                        }
                    });
            });
        },
        cancel: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("div.user-state input").on("click", this.changeState);
            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("form div.add-company a.btn-add-company").on("click", $.proxy(function () {
                this.addUserCompany();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("form div.user-cmpy a.btn-removeCompany").on("click", $.proxy(function () {
                this.removeUserCompany(event);
                return false;
            }, this));

            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});


define([
    'views/baseView',
    'models/crud/userModel',
    'models/crud/companyModel',
    'models/crud/rolModel',
    'models/crud/groupModel',

    'text!templates/crud/crudBase.html',
    'text!templates/crud/crudForm.html',
    'text!templates/crud/user/super/userCreate.html',
    'text!templates/crud/user/super/userEditCmpyItem.html',
], function (BaseView, UserModel, CompanyModel, RolModel, GroupModel,
        BaseTmp, FormTmp, UniqTmp, cmpyItemTemplate) {
    var view = BaseView.extend({

        $form: null,

        render: function () {
            toggleLoading(true);
            $("div[data-rel='crud_user']").remove();
            var that = this;

            var baseTemplate = Handlebars.compile(BaseTmp);
            var formTemplate = Handlebars.compile(FormTmp);

            var dataBaseOptions = {
                id: that._uId,
                dataRel: "crud_user", // cuidado, ref en js
                tmpClass: "user_new", // cuidado, ref en css
                title: translate("_newUser")
            };

            var html = baseTemplate(dataBaseOptions);
            //var html2 = formTemplate();

            (new CompanyModel()).list(function (dataCompany) {
                var uniqTemplate = Handlebars.compile(UniqTmp);


                var dataUniqTemplate = {
                    company: dataCompany
                };

                var html3 = uniqTemplate(dataUniqTemplate);

                this.$el.append(html);
                this.$el.find(".crud_content").append(html3);
                //$("div[data-id='" + that._uId + "']").find("div.abm-content").append(html2);
                //$("div[data-id='" + that._uId + "']").find("div.form-content").append(html3);

                postRender(that.$el);

                that.addHandlers();
                toggleLoading(false);
            });
        },
        save: function () {
            var _uId = this._uId;

            var _userForm = $("div[data-id='" + _uId + "']").find("form");
            if (!$(_userForm).validate().errorList.length > 0) {

                var listCompanies = $("div[data-id='" + _uId + "']").find("div.user-company-items");
                if (listCompanies.length > 0) {
                    var _name = $("div[data-id='" + _uId + "']").find("div.user-name input").val(),
                    _userLogin = $("div[data-id='" + _uId + "']").find("div.user-login input").val(),
                    _password = $("div[data-id='" + _uId + "']").find("div.user-password input").val(),
                    _email = $("div[data-id='" + _uId + "']").find("div.user-email input").val(),
                    _state = '0' != $("div[data-id='" + _uId + "']").find("div.user-state input").val();

                    var userCompanyId = "",
                        _rolId = "",
                        groupItem = "";
                    var userCompaniesData = [];
                    for (var k = 0; k < listCompanies.length; k++) {
                        userCompanyId = $(listCompanies[k]).find("div.user-company-assigned").attr("data-value");
                        _rolId = $(listCompanies[k]).find("div.user-rol a div").attr("data-value");
                        if (_rolId == undefined) {
                            _rolId = $(listCompanies[k]).find("div.user-rol a").attr("data-value");
                        }

                        _groupItem = $(listCompanies[k]).find("div.user-group a");
                        var assignedGroups = [];

                        var auxRowGroups = $(_groupItem).attr("data-value");
                        if (auxRowGroups != undefined) {
                            var splitGroups = auxRowGroups.split(",");

                            for (var h = 0; h < splitGroups.length; h++) {
                                assignedGroups[h] = {
                                    groupId: splitGroups[h]
                                };
                            }
                        }

                        userCompaniesData[k] = {
                            companyId: userCompanyId,
                            rolId: _rolId,
                            groups: assignedGroups
                        };
                    }

                    var user = {
                        fullName: _name, userLogin: _userLogin,
                        active: _state, email: _email, password: _password,
                        userCompanies: userCompaniesData
                    };
                    var userMod = new UserModel();

                    userMod.Create(user, function () {
                        require(['controllers/abmManagers/userManager'], function (Controller) {
                            (new Controller()).show();
                        });
                    });
                } else
                    $.gritter.add({
                        title: translate("_wait"),
                        text: translate("_noCompanyAssigned"),
                        image: null,
                        time: '3000'
                    });
            }
        },
        changeState: function () {
            this.checked ? $(this).attr('value', 1) : $(this).attr('value', 0);
        },
        refreshListLabels: function () {
            $("div[data-id='" + this._uId + "']").find("div.cmpy-list").css({
                "display": ($("div[data-id='" + this._uId + "']").find("div.user-company-assigned").length == "0") ? "none" : "inline-block"
            });
        },
        addUserCompany: function () {
            var _this = this;
            var divToAddUser = $("div[data-id='" + _this._uId + "']").find("div.user-cmpy");

            var listCompanies = $("div[data-id='" + _this._uId + "']").find("div.user-company-assigned");
            // leer company seleccionada.
            var selCmpyId = $("div[data-id='" + _this._uId + "']").find("div.add-company select").val();
            for (var i = 0 ; i < listCompanies.length ; i++) {
                if ($(listCompanies[i]).attr("data-value") == selCmpyId) {
                    $.gritter.add({
                        title: translate("_wait"),
                        text: translate("_companyAlreadyAssigned"),
                        image: null,
                        time: '3000'
                    });
                    return;
                }
            }

            var cmpyMod = new CompanyModel(),
                rolMod = new RolModel(),
                groupMod = new GroupModel();
            var template = Handlebars.compile(cmpyItemTemplate);
            cmpyMod.GetCompany(selCmpyId, function (dataCompany) {
                rolMod.List(selCmpyId, function (dataRol) {
                    groupMod.List(selCmpyId, function (dataGroup) {
                        var data = {
                            groups: dataGroup,
                            rol: dataRol,
                            company: dataCompany
                        };
                        var html = template(data);
                        this.$(divToAddUser).append(html);
                        _this.refreshListLabels();
                        var newItem = $(divToAddUser).find("div.user-company-items").last();
                        if (dataRol.length > 0) { // si la company tiene roles
                            var _rolItem = $(newItem).find("div.user-rol a");
                            var rolList = [{ value: "", text: "" }];

                            for (var ii = 0; ii < dataRol.length; ii++) {
                                rolList[ii] = {
                                    value: dataRol[ii].rolId,
                                    text: dataRol[ii].name
                                }
                            };
                            _rolItem.editable({
                                pk: 1,
                                source: rolList,
                                success: function (response, newValue) {
                                    $(this).attr("data-value", newValue);
                                }
                            });
                        }

                        if (dataGroup.length > 0) { // si la company tiene grupos
                            var _groupItem = $(newItem).find("div.user-group a");

                            var groupsList = [{ value: "", text: "" }];

                            for (var i = 0; i < dataGroup.length; i++) {
                                groupsList[i] = {
                                    value: dataGroup[i].groupId,
                                    text: dataGroup[i].name
                                }
                            };
                            _groupItem.editable({
                                pk: 1,
                                source: groupsList,
                                success: function (response, newValue) {
                                    $(this).attr("data-value", newValue);
                                }
                            });
                        }
                        $(newItem).find("a.btn-removeCompany").on("click", $.proxy(function () {
                            _this.removeUserCompany(event);
                            return false;
                        }, _this));
                    });
                });
            });
        },
        removeUserCompany: function (e) {
            var _toRemove = $(e.currentTarget).parent("div").parent("div");
            var _this = this;

            require(['controllers/common/showModal'], function (Controller) {
                (new Controller()).show(
                    {
                        title: translate("_deleteUserCompany"),
                        text: translate("_sure_delete_user_company"),
                        buttons: [
                            { "title": translate("yes"), "css": "primary", "code": "yes" },
                            { "title": translate("no"), "code": "no" }
                        ],
                        callback: function (code) {
                            if (code == "yes") {
                                toggleLoading(true);
                                _toRemove.prev("hr").remove();
                                _toRemove.remove();
                                _this.refreshListLabels();
                            }
                            // falta meter el toggleLoading en el callback de refreshListLabels
                            toggleLoading(false);
                        }
                    });
            });
        },
        cancel: function () {
            require(['controllers/abmManagers/userManager'], function (Controller) {
                (new Controller()).show();
            });
        },
        addHandlers: function () {
            $("div[data-id='" + this._uId + "']").find("div.user-state input").on("click", this.changeState);

            $("div[data-id='" + this._uId + "']").find("form").on("submit", $.proxy(function () {
                this.save();
                return false;
            }, this));

            $("div[data-id='" + this._uId + "']").find("div.submit button.btn-cancel").on("click", $.proxy(function () {
                this.cancel();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("form div.add-company a.btn-add-company").on("click", $.proxy(function () {
                this.addUserCompany();
                return false;
            }, this));
            $("div[data-id='" + this._uId + "']").find("div.abm-top-options a.btn-close").on("click", this.cancel);
        }
    });
    return view;
});